package com.jin.jpa.wrapper.util;

import com.jin.jpa.wrapper.support.FieldFunction;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.Objects;

/**
 * @Author: yuanxiuyao
 * @Date: 2024/1/4 16:18
 * @PackageName: org.example.jpa.wrapper.util
 * @Version 1.0
 */
public class LambdaUtils {

    public static <T> PropertyDescriptor extract(FieldFunction<T, ?> func, Class instanceClass) {
        return convertUShadowLambdaMeta(SerializedLambda.extract(func), instanceClass);
    }

    public static PropertyDescriptor convertUShadowLambdaMeta(SerializedLambda serializedLambda, Class instanceClass){
        String implMethodName = serializedLambda.getImplMethodName();
        PropertyDescriptor[] allPropertyDescriptor = findAllPropertyDescriptor(instanceClass);
        return Arrays.stream(allPropertyDescriptor).filter(o -> Objects.equals(o.getReadMethod().getName(), implMethodName))
                .findFirst().get();
    }

    public static PropertyDescriptor[] findAllPropertyDescriptor(Class clazz){
        try {
            return Introspector.getBeanInfo(clazz).getPropertyDescriptors();
        } catch (IntrospectionException e) {
            throw new RuntimeException(e);
        }
    }

}
